package wty;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.mindrot.jbcrypt.BCrypt;
import wty.Bee.User;
import wty.Bee.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@WebServlet("/wty/register")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("进入post注册");

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        //判断 HTTP 请求是否采用了multipart/form-data格式
        if (!ServletFileUpload.isMultipartContent(request)) {
            response.getWriter().write("{\"error\":\"Invalid request format\"}");
            return;
        }

        try {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            List<FileItem> items = upload.parseRequest(request);
            Map<String, String> formFields = new HashMap<>();
            byte[] avatarData = null;

            for (FileItem item : items) {
                if (item.isFormField()) {
                    formFields.put(item.getFieldName(), item.getString("UTF-8"));
                } else if ("avatar".equals(item.getFieldName()) && !item.getName().isEmpty()) {
                    try (InputStream fileStream = item.getInputStream();
                         ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {

                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = fileStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }
                        avatarData = outputStream.toByteArray();
                    }
                }
            }

            // 创建User对象
            User user = new User();
            user.setUserid(UUID.randomUUID().toString().substring(0,24));

            // 设置基本属性
            String username = formFields.get("username");
            String password = formFields.get("userpasswd");
            String email = formFields.get("email");
            String phone = formFields.get("phone");
            String gender = formFields.get("gender");

            if (username != null) user.setUsername(username);
            if (password != null) user.setPassword(BCrypt.hashpw(password, BCrypt.gensalt()));
            if (email != null) user.setEmail(email);
            if (phone != null) user.setPhone(phone);
            if (gender != null) user.setGender(gender);

            // 设置头像二进制数据
            user.setAvatar(avatarData);

            // 设置其他默认值
            user.setRole("user");
            user.setBirthday(new Date());

            // 插入数据库
            UserDao userDao = new UserDao();
            userDao.insert(user);

            response.getWriter().write("{\"success\":\"register success\"}");

        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("{\"error\":\"Registration failed: " + e.getMessage() + "\"}");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.getWriter().write("{\"error\":\"GET method not supported\"}");
    }
}